package com.huluobo.a2107mvpimdemo.chat.presenter;

import android.util.Log;

import com.huluobo.a2107mvpimdemo.base.BasePresenter;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LC on 2023/10/6.
 */
public class ChatPresenter extends BasePresenter<ChatContract.View> implements ChatContract.Presenter {
    //消息列表数据源
    public List<EMMessage> messages = new ArrayList<>();

    private static final int PAGE_SIZE = 10;

    @Override
    public void sendMessage(String content, String username) {
        //创建出了一条消息,文本消息
        EMMessage emMessage = EMMessage.createTextSendMessage(content, username);
        //消息状态的回调,成功时,给v层发送成功,失败时给v层发送失败消息
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                if (isAttach()) {
                    getView().onSendMessageSuccess();
                }
            }

            @Override
            public void onError(int code, String error) {
                if (isAttach()) {
                    getView().onSendMessageFailed(error);
                }
            }
        });

        //更新数据源中的消息
        messages.add(emMessage);
        if (isAttach()) {
            getView().onStartSendMessage();
        }
        //通过环信发送消息
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        Log.i("TagA", "messages:" + messages.size());
    }

    @Override
    public void addMessage(String username, List<EMMessage> messages) {
        //接收到的消息需要加入到当前的消息列表中
        this.messages.addAll(messages);

        //只要进入到聊天页面,就把对应username的所有会话记录标记为已读
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        conversation.markAllMessagesAsRead();
    }

    @Override
    public void loadMessage(String username) {
        EMConversation emConversation = EMClient.getInstance().chatManager().getConversation(username);
        emConversation.markAllMessagesAsRead();//设置所有历史消息为已读
        messages.addAll(emConversation.getAllMessages());//在消息列表中加入所有历史消息
        if (isAttach()) {
            getView().onMessageLoaded();
        }
    }

    @Override
    public void loadMoreMessage(String username) {
        EMConversation emConversation = EMClient.getInstance().chatManager().getConversation(username);
        String startId = messages.get(0).getMsgId();//查询历史记录的起始位置,也就是当前聊天记录第0位的位置
        List<EMMessage> emMessages = emConversation.loadMoreMsgFromDB(startId, PAGE_SIZE);
        messages.addAll(0, emMessages);//加载历史聊天记录时,不能从list的末尾添加,需要从list的头部进行添加
        //index = 0 的位置,这样添加的聊天记录才符合逻辑
        if (isAttach()) {
            getView().onMoreMessageLoaded(emMessages.size());//使用emMessages 的size,是为了保证如果数据库或者后台服务器中不够10条记录的时候,
            // 需要加载具体的size
        }
    }
}
